package com.mall.web.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 高德地图的经度
 * 
 * @author lihaiyang
 *
 */
public class GetGaodeLongitudeAndLatitudeUtil {
	private static String API = "http://restapi.amap.com/v3/geocode/geo?key=<key>&s=rsv3&address=<address>";

	private static String KEY = "aa4a48297242d22d2b3fd6eddfe62217";

	private static Pattern pattern = Pattern.compile("\"location\":\"(\\d+\\.\\d+),(\\d+\\.\\d+)\"");
//	public static int FACTORS = 1000000;
	static {
		init();
	}

	private static void init() {

		API = API.replaceAll("<key>", KEY);
	}

	public static Double getLongitudeByAddress(String address) throws IOException {
		try {
			String requestUrl = API.replaceAll("<address>", URLEncoder.encode(address, "UTF-8"));

			requestUrl = HttpClientHelper.INSTANCE.get(requestUrl);
			if (requestUrl != null) {
				Matcher matcher = pattern.matcher(requestUrl);
				if (matcher.find() && matcher.groupCount() == 2) {
					double[] gps = new double[2];
					gps[0] = Double.valueOf(matcher.group(1));
					return new Double(gps[0]);
				}
			}
		} catch (UnsupportedEncodingException e) {
		}

		return null;
	}

	public static Double getLatitudeByAddress(String address) throws IOException {
		try {
			String requestUrl = API.replaceAll("<address>", URLEncoder.encode(address, "UTF-8"));

			requestUrl = HttpClientHelper.INSTANCE.get(requestUrl);
			if (requestUrl != null) {
				Matcher matcher = pattern.matcher(requestUrl);
				if (matcher.find() && matcher.groupCount() == 2) {
					double[] gps = new double[2];
					gps[1] = Double.valueOf(matcher.group(2));
					return new Double(gps[1]);
				}
			}
		} catch (UnsupportedEncodingException e) {
		}

		return null;
	}

//	public static void main(String[] args) throws IOException {
//		System.out.println(getLatitudeByAddress("绍兴市鲁迅中路179号"));
//
//	}

}
